import AsyncStorage from '@react-native-async-storage/async-storage';

// 定义消息和事件类型
type MessageType = {
  id: string;
  type: 'text' | 'image' | 'audio' | 'video' | 'media' | 'voice_call';
  content: string;
  media?: MediaType[];
  isSelf?: boolean;
  timestamp: number;
  callStatus?: 'calling' | 'connected' | 'ended' | 'rejected';
  to?: string;
};

type MediaType = {
  type: 'image' | 'video';
  uri: string;
};

// 定义一个通用的数据类型
type SocketData = {
  [key: string]: string | number | boolean | undefined;
};

// 修改 EventHandler 类型
type EventHandler = (data: MessageType | string | SocketData) => void;

class SocketService {
  private static STORAGE_KEY = 'chat_messages';
  private static MOCK_DELAY = 500;
  private listeners: Map<string, Set<EventHandler>>;

  constructor() {
    this.listeners = new Map();
  }

  connect() {
    console.log('Mock socket connected');
  }

  disconnect() {
    console.log('Mock socket disconnected');
  }

  on(event: string, handler: EventHandler) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }
    this.listeners.get(event)?.add(handler);

    return () => {
      this.listeners.get(event)?.delete(handler);
    };
  }

  public emit(event: string, data: MessageType | string | SocketData) {
    try {
      const handlers = this.listeners.get(event);
      if (handlers) {
        handlers.forEach(handler => {
          try {
            handler(data);
          } catch (error) {
            console.error(`处理事件 ${event} 失败:`, error);
          }
        });
      }
    } catch (error) {
      console.error(`发送事件 ${event} 失败:`, error);
    }
  }

  async sendMessage(message: MessageType) {
    try {
      // 存储发送的消息
      const sentMessage = {
        ...message,
        isSelf: true,
        timestamp: Date.now(),
      };
      console.log(sentMessage);
      
      await this.storeMessage(sentMessage);

      // 模拟服务器回复
      setTimeout(async () => {
        let response: MessageType;
        
        if (message.type === 'audio') {
          // 使用发送者的音频URI作为回复
          response = {
            id: `server_${Date.now()}`,
            type: 'audio',
            content: message.content, // 使用相同的音频文件
            isSelf: false,
            timestamp: Date.now(),
          };
        } else {
          // 其他消息类型的处理保持不变
          response = {
            id: `server_${Date.now()}`,
            type: message.type,
            content: `回复: ${message.content}`,
            isSelf: false,
            timestamp: Date.now(),
            media: message.media,
          };
        }

        await this.storeMessage(response);
        this.emit('message', response);
      }, SocketService.MOCK_DELAY);

    } catch (error) {
      console.error('处理消息失败:', error);
    }
  }

  handleVoiceCall() {
    // 模拟通话建立过程
    setTimeout(() => {
      try {
        this.emit('call_status', 'connected');
      } catch (error) {
        console.error('发送通话状态失败:', error);
      }
    }, 2000);
  }

  private async storeMessage(message: MessageType) {
    try {
      const existingMessages = await AsyncStorage.getItem(SocketService.STORAGE_KEY);
      const messages = existingMessages ? JSON.parse(existingMessages) : [];
      messages.push(message);
      await AsyncStorage.setItem(SocketService.STORAGE_KEY, JSON.stringify(messages));
    } catch (error) {
      console.error('存储消息失败:', error);
    }
  }

  async getMessageHistory(): Promise<MessageType[]> {
    try {
      const messages = await AsyncStorage.getItem(SocketService.STORAGE_KEY);
      return messages ? JSON.parse(messages) : [];
    } catch (error) {
      console.error('获取历史消息失败:', error);
      return [];
    }
  }

  async clearHistory() {
    try {
      await AsyncStorage.removeItem(SocketService.STORAGE_KEY);
    } catch (error) {
      console.error('清空历史消息失败:', error);
    }
  }

  isConnected(): boolean {
    return true;
  }

  getSocket(): null {
    return null;
  }

  off(event: string, handler: EventHandler) {
    const handlers = this.listeners.get(event);
    if (handlers) {
      handlers.delete(handler);
    }
  }
}

const socketService = new SocketService();

export const sendMessage = (message: MessageType) => {
  return socketService.sendMessage(message);
};

export const listenMessages = (callback: (message: MessageType) => void) => {
  return socketService.on('message', callback);
};

export default socketService;
